import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const serviceObj = {
  timeout: 30 * 10000 // 请求超时时间
}
const service = axios.create(serviceObj)

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    if (process.env.NODE_ENV === 'production') {
      config.url = process.env.API_ROOT + config.url
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  requestResponseHandler,
  requestErrorHandler
)

export default service

export function requestResponseHandler (response) {
  return response.data
}

export function requestErrorHandler (error) {
  if (!error.response) {
    console.log('请求超时')
  } else {
    if (error.response.status === 401) {
      MessageBox.confirm(
        '你已被登出，可以取消继续留在该页面，或者重新登录',
        '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
  }
  return Promise.reject(error)
}
